package com.zhangxin.aiInterview.controller;

import com.zhangxin.aiInterview.annotation.AuthCheck;
import com.zhangxin.aiInterview.common.BaseResponse;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.common.ResultUtils;
import com.zhangxin.aiInterview.constant.UserConstant;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.manager.redis.rate_limiter.RateLimitManager;
import com.zhangxin.aiInterview.manager.work_flow.generate_resume.GenerateResume;
import com.zhangxin.aiInterview.model.dto.resume.ResumeSearchRequest;
import com.zhangxin.aiInterview.model.dto.resume.UploadFileRequest;
import com.zhangxin.aiInterview.model.entity.ResumeAnalysisResult;
import com.zhangxin.aiInterview.model.po.ExtractedResumePO;
import com.zhangxin.aiInterview.model.vo.ResumeVO;
import com.zhangxin.aiInterview.service.ResumeAnalysisResultService;
import com.zhangxin.aiInterview.service.ResumeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 简历文件接口
 */
@RestController
@RequestMapping("/resume")
@Slf4j
public class ResumeController {


    @Resource
    private ResumeService resumeService;
    @Resource
    private ResumeAnalysisResultService resumeAnalysisResultService;
    @Resource
    private RateLimitManager rateLimitManager;

    /**
     * 简历上传
     *
     * @param multipartFile 简历文件数据
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Long> uploadFile(@RequestPart("file") MultipartFile multipartFile, UploadFileRequest uploadFileRequest,  HttpServletRequest request) {
        //上传简历
        Long resumeId = resumeService.uploadFile(multipartFile, uploadFileRequest, request, false,null);
        //前端渲染简历
        return ResultUtils.success(resumeId);
    }

    /**
     * 公共接口：简历上传并同步分析
     * 提供给外部应用程序直接调用，无需权限校验
     * 同步执行简历上传和内容分析，返回完整分析结果
     *
     * @param multipartFile 简历文件数据
     * @param positionName 面试岗位名称
     * @param companyName 公司名称
     * @return 包含简历ID和分析结果的完整数据
     */
    @PostMapping("/public/upload")
    public BaseResponse<String> publicUploadResume(
            @RequestPart("file") MultipartFile multipartFile,
            @RequestParam("positionName") String positionName,
            @RequestParam("companyName") String companyName,
            HttpServletRequest request) {

        try {
            // 获取客户端IP
            String clientIp = rateLimitManager.getClientIpAddress(request);
            String rateLimitKey = "AI_interview:public:rateLimiting:resumeAnalyze:" + clientIp;

            // 检查限流（1分钟1次）
            if (!rateLimitManager.isAllowed(rateLimitKey, 1, 60)) {
                log.warn("简历分析接口触发限流：IP={}", clientIp);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "请求过于频繁，请稍后再试");
            }

            // 记录日志
            log.info("公共接口收到简历上传请求：岗位={}, 公司={}, IP={}", positionName, companyName, clientIp);

            // 调用简历分析分析方法
            String result = resumeService.uploadAndAnalyzeResume(
                    multipartFile, positionName, companyName);

            return ResultUtils.success(result);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("公共接口简历上传分析失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "简历上传分析失败：" + e.getMessage());
        }
    }

    /**
     * 搜索用户简历
     * @param resumeSearchRequest
     * @param request
     * @return
     */
    @GetMapping("/search")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<List<ResumeVO>> searchResume(ResumeSearchRequest resumeSearchRequest, HttpServletRequest request) {
        List<ResumeVO> resumeVOList = resumeService.searchResume(resumeSearchRequest,request);
        return ResultUtils.success(resumeVOList);
    }

    /**
     * 获取解析完成的简历(因为只有解析完成的简历才能被用于面试)
     * @param request
     * @return
     */
    @GetMapping("/getExtractedResume")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<List<ExtractedResumePO>> getExtractedResume(HttpServletRequest request) {
        List<ExtractedResumePO> extractedResumePOList = resumeService.getExtractedResumeByUserId(request);
        return ResultUtils.success(extractedResumePOList);
    }

    /**
     * 获取简历分析结果
     * @param resumeId
     * @return
     */
    @GetMapping("/get/resumeAnalysisResult")
    public BaseResponse<ResumeAnalysisResult> getResumeAnalyzeResult(Long resumeId) {
        ResumeAnalysisResult resumeAnalysisResult = resumeAnalysisResultService.lambdaQuery()
                .eq(ResumeAnalysisResult::getResumeId, resumeId)
                .one();
        return ResultUtils.success(resumeAnalysisResult);
    }

    /**
     * 删除简历分析记录
     * @param resumeId
     * @param request
     * @return
     */
    @GetMapping("/delete")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteResume(@RequestParam("resumeId") Long resumeId,HttpServletRequest request) {
        boolean b = resumeService.deleteResume(resumeId,request);
        return ResultUtils.success(b);
    }

    /**
     * 生成智能简历
     * @param jsonStr
     * @return
     */
    @PostMapping("/generate")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<String> generateResume(@RequestBody String jsonStr){
        System.out.println(jsonStr);
        return ResultUtils.success(GenerateResume.generateResume(jsonStr));
    }
}